<template>
  <el-container class="wrapper">
    <el-main>
      <el-table :data="loading ? [] : currentPage()">
        <el-table-column label="用户ID" prop="id"></el-table-column>
        <el-table-column label="用户名" prop="name"></el-table-column>
        <el-table-column label="手机号" prop="phoneNumber"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="最近登录时间" prop="lastLoginTime"></el-table-column>
        <el-table-column label="用户类型" prop="role"></el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              :disabled="myself === null || scope.row.id === myself.id || myself.role <=  scope.row.role"
              size="small"
              type="text"
              @click.native.prevent="modifyRow(scope.$index)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="pageIndex"
        :page-size="pageSize"
        :page-sizes="[1, 10, 20, 50, 100]"
        :total="pageCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
      <el-dialog :visible.sync="modifying" width="600px">
        <el-form :model="modifyForm" label-position="right" label-width="120px">
          <el-form-item label="用户ID">
            <el-input v-model="modifyForm.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input v-model="modifyForm.name" disabled></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-row justify="space-between" type="flex">
              <el-col :span="18">
                <el-input v-model="modifyForm.phoneNumber" disabled></el-input>
              </el-col>
              <el-col :span="5">
                <el-button style="width: 100%;" type="danger" @click="deletePhoneNumber">删除</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-row justify="space-between" type="flex">
              <el-col :span="18">
                <el-input v-model="modifyForm.email" disabled></el-input>
              </el-col>
              <el-col :span="5">
                <el-button style="width: 100%;" type="danger" @click="deleteEmail">删除</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="最近登录时间">
            <el-input v-model="modifyForm.lastLoginTime" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户类型">
            <el-radio-group v-model="modifyForm.role">
              <el-radio-button :disabled="myself === null || myself.role <= 0" :label="0">普通用户</el-radio-button>
              <el-radio-button :disabled="myself === null || myself.role <= 1" :label="1">管理员</el-radio-button>
              <el-radio-button :disabled="myself === null || myself.role <= 2" :label="2">超级管理员</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button style="margin-right: 20px" type="danger" @click="deleteUser">删除用户</el-button>
          <el-button @click="cancelModify">取 消</el-button>
          <el-button type="primary" @click="submitModify">确 定</el-button>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
export default {
  name: "user-list",
  data() {
    return {
      totalNum: 0,
      userList: [],
      pageIndex: 0,
      pageSize: 10,
      loading: false,
      modifyIndex: null,
      modifyForm: {
        id: null,
        name: null,
        phoneNumber: null,
        email: null,
        lastLoginTime: null,
        role: null,
      },
    }
  },
  methods: {
    queryTotalNum: function () {
      return this.$axios.get("/api/admin/count")
        .then(res => {
          const code = res.data.responseCode;
          if (code === 200)
            this.totalNum = res.data.responseData;
          else
            this.totalNum = 0;
        });
    },
    doPaging: function () {
      for (let i = 0; i < this.pageCount; i++) {
        this.userList[i] = [];
      }
    },
    queryPage: function (index, size) {
      this.$axios.post("/api/admin/list", {
        pageSize: size,
        pageNumber: index + 1,
      })
        .then(res => {
          const code = res.data.statusCode;
          if (code === 200) {
            this.userList[index] = res.data.responseData.records;
            this.loading = false;
          } else {
            this.$message.error("请求失败！");
          }
        });
    },
    getPage: function (index, refresh = false) {
      if (!refresh && this.userList[index]) {
        return this.userList[index];
      } else {
        this.loading = true;
        this.queryPage(index, this.pageSize);
        return []
      }
    },
    currentPage: function (refresh = false) {
      return this.getPage(this.pageIndex, refresh);
    },
    modifyRow: function (index) {
      this.modifyForm = {...this.userList[this.pageIndex][index]};
      this.modifyIndex = index;
    },
    cancelModify: function () {
      this.modifyIndex = null;
    },
    submitModify: function () {
      this.$axios.put("/api/admin/update", this.modifyForm)
        .then(res => {
          const code = res.data.statusCode;
          if (code === 200) {
            this.$message.success("修改成功！");
            this.currentPage(true);
            this.modifyIndex = null;
          } else {
            throw new Error("修改失败！");
          }
        })
        .catch(() => {
          this.$message.error("修改失败！");
        })
    },
    deletePhoneNumber: function () {
      this.$confirm("此操作将删除用户手机号, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.modifyForm.phoneNumber = null;
        this.$message.success("删除成功!");
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },
    deleteEmail: function () {
      this.$confirm("此操作将删除用户邮箱, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.modifyForm.email = null;
        this.$message.success("删除成功!");
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },
    deleteUser: function () {
      this.$confirm("此操作将彻底删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios.delete(`/api/admin/remove/${this.modifyForm.id}`)
          .then(res => {
            const code = res.data.statusCode;
            if (code === 200) {
              this.$message.success("删除成功!");
              this.modifyIndex = null;
            } else {
              this.$message.error("删除失败！");
            }
          })
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      });
    },
    handleSizeChange: function (val) {
      this.pageIndex = val;
    },
    handleCurrentChange: function (val) {
      this.pageIndex = val;
    },
  },
  computed: {
    pageCount: function () {
      return Math.ceil(this.totalNum / this.pageSize);
    },
    myself: function () {
      return this.$store.state.selfInfo;
    },
    modifying: {
      get: function () {
        return this.modifyIndex !== null;
      },
      set: function () {
        this.modifyIndex = null;
      }
    }
  },
  mounted() {
    this.queryTotalNum()
      .then(() => this.doPaging())
  }
}
</script>

<style scoped>

</style>